package com.egao.gps.service.impl;

import com.egao.common.core.damon.constant.UserConstant;
import com.egao.common.core.damon.results.PageResult2;
import com.egao.common.core.damon.utils.DateUtil;
import com.egao.common.core.damon.utils.HttpsUtils;
import com.egao.common.core.damon.utils.StringUtil;
import com.egao.common.core.damon.utils.Utils;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.biz.UserBiz;
import com.egao.common.system.entity.User;
import com.egao.gps.ZjxlGps;
import com.egao.gps.dao.CarPositionDao;
import com.egao.gps.entity.CarPosition;
import com.egao.gps.entity.CarPosition2;
import com.egao.gps.service.CarPositionService;
import com.egao.gps.utils.DistanceUtil;
import com.egao.gps.utils.MapNavUtil;
import com.egao.gzh.entity.TempSend;
import com.egao.gzh.service.SettingGzh;
import com.egao.orderB.biz.AddressFactoryBiz;
import com.egao.orderB.biz.BillBiz;
import com.egao.orderB.entity.AddressFactory;
import com.egao.orderB.entity.Bill;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author Damon
 * @create 2020-11-17 14:31
 */
@Service
public class CarPositionServiceImpl implements CarPositionService {

    @Autowired
    private CarPositionDao carPositionDao;
    @Autowired
    private BillBiz billBiz;
    @Autowired
    private AddressFactoryBiz addressFactoryBiz;
    @Autowired
    private UserBiz userBiz;

    @Override
    public JsonResult listPage(PageResult2 page, CarPosition carPosition) {
        return carPositionDao.listPage(page,carPosition);
    }

    @Override
    public JsonResult list(CarPosition carPosition) {
        if(Utils.isNotEmpty(carPosition.getDate1())&&Utils.isNotEmpty(carPosition.getDate2())){
            try {
                SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date begin = dfs.parse(carPosition.getDate1());
                Date end = dfs.parse(carPosition.getDate2());
                long between = (end.getTime() - begin.getTime()) / 1000;//除以1000是为了转换成秒
                long day1 = between / (24 * 3600);
                long hour1 = between % (24 * 3600) / 3600;
                long minute1 = between % 3600 / 60;
                long second1 = between % 60 / 60;
//                System.out.println("" + day1 + "天" + hour1 + "小时" + minute1 + "分" + second1 + "秒");
                if(day1<1) {
                    return JsonResult.ok().setData(carPositionDao.list(carPosition));
                }
            } catch (Exception e) {
                return JsonResult.error("时间不能大于一天");
            }
        }
        return JsonResult.error();
    }

    @Override
    public String getDistanceByBillId(CarPosition carPosition) {
        List<CarPosition> carPositions = carPositionDao.list(carPosition);
        double m = 0;
        if(carPositions != null && carPositions.size() > 0) {
            for (int i = 0; i < carPositions.size()-1; i ++) {
                CarPosition cp1 = carPositions.get(i);
                CarPosition cp2 = carPositions.get(i+1);

                if(!StringUtil.isBlank(cp1.getLon(), cp1.getLat(), cp2.getLon(), cp2.getLat())) {
                    m += DistanceUtil.getDistance(Double.valueOf(cp1.getLon()),Double.valueOf(cp1.getLat()),
                            Double.valueOf(cp2.getLon()),Double.valueOf(cp2.getLat()));
                }
            }
        }
        return String.format("%.1f", m);
    }

    @Override
    public JsonResult trajectory(CarPosition carPosition) {
        if(carPosition!=null && Utils.isEmpty(carPosition.getVno())){
            return JsonResult.error("请填写车牌");
        }
        List<CarPosition> carPositions = ZjxlGps.vHisTrack24(carPosition.getVno(), carPosition.getDate1(),carPosition.getDate2());
        return JsonResult.ok().setData(carPositions);
    }

    @Override
    public JsonResult normalCarList(CarPosition carPosition) {
        if(carPosition==null || Utils.isEmpty(carPosition.getVno())){
            return JsonResult.error("请填写车牌");
        }
//        String vnoStr = "'"+carPosition.getVno().replaceAll(",", "','")+"'";
        List<String> carNoes = Arrays.asList(carPosition.getVno().split(","));
        List<Bill> bills = billBiz.normalCarList(carNoes);
        List<CarPosition> carPositions = new ArrayList<>();
        CarPosition c = null;
        for (String str: carNoes) {
            boolean retc = true;
            c = new CarPosition();
            c.setVno(str);
            for (Bill b: bills) {
                if(str.equals(b.getCarNo())) {
                    c.setType("出行中");
                    retc = false;
                }
            }
            if (retc) {
                c.setType("未出行");
            }
            carPositions.add(c);
        }
        return JsonResult.ok().setData(carPositions);
    }

    @Override
    public JsonResult syncList(CarPosition carPosition) {
        Bill bill3 = new Bill();
        if(carPosition!=null) {
            if(Utils.isNotEmpty(carPosition.getCustomer())){
                bill3.setCustomer(carPosition.getCustomer());
            }
            if(Utils.isNotEmpty(carPosition.getBillId())){
                bill3.setId(carPosition.getBillId());
            }
            if(Utils.isNotEmpty(carPosition.getVno())){
                bill3.setCarNo(carPosition.getVno());
            }
        }
        List<Bill> bills = billBiz.findCarName(bill3);
        String[] strs = {"",""};
        String vno = carPosition.getVno();
        if(bills != null && bills.size()>0) {
            for (Bill b: bills) {
                if(Utils.isNotEmpty(vno)){
                    vno = vno.replace(","+b.getCarNo(),"").replace(b.getCarNo(),"");
                }
                strs[0] += b.getCarNo()+"_2,";
                strs[1] += b.getId()+",";
            }
            strs[0] = strs[0].substring(0,strs[0].length()-1);
            strs[1] = strs[1].substring(0,strs[1].length()-1);
        }
        if(Utils.isNotEmpty(vno)){
            String[] vnos = vno.split(",");
            for (String s : vnos) {
                strs[0] += ","+s+"_2";
                strs[1] += ",无id";
            }
        }

        List<CarPosition> carPositions = ZjxlGps.vLastLocationV4(strs[0],strs[1]);
//        System.out.println(carPositions.size()+"3333333");
        if (carPositions != null && carPositions.size() > 0) {
            for (CarPosition c : carPositions) {
                for (Bill b: bills) {
                    if(c.getVno().equals(b.getCarNo())) {
                        AddressFactory addressFactory = new AddressFactory();
                        addressFactory.setBillId(b.getId());
                        List<AddressFactory> addressFactories = addressFactoryBiz.list(addressFactory, new User(1));
                        String add = "";
                        if (Utils.isNotEmpty(addressFactories)) {
                            for (AddressFactory af : addressFactories) {
                                add += af.getFaddress()+", ";
                            }
                        }
                        c.setDriver(b.getDriver());
                        c.setDriverPhone(b.getDriverPhone());
                        c.setBillOfLading(b.getBillOfLading());
                        c.setCustomer(b.getCustomer());
                        c.setCarTeam(b.getCarTeam());
                        c.setFactoryAddress(add);
                        c.setAddressFactoryList(addressFactories);
                        c.setAddress(b.getAddress());
                        c.setUpyard(b.getUpYard());
                        c.setUpyardLongitude(b.getUpYardLongitude());
                        c.setUpyardLatitude(b.getUpYardLatitude());
                        c.setDock(b.getDock());
                        c.setDockLongitude(b.getDockLongitude());
                        c.setDockLatitude(b.getDockLatitude());
                        c.setState(b.getState());
//                        System.out.println(c.getLat() + "," + c.getLon()+"=============1111");
                        try {
                            double[] gps = DistanceUtil.toTX(c.getLat() + "," + c.getLon());
                            c.setLat(gps[1]+"");
                            c.setLon(gps[0]+"");
//                            System.out.println(c.getLat() + "," + c.getLon()+"=============222222222");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return JsonResult.ok().setData(carPositions);
    }

    public static void main(String[] args) {
        double f = 111231.5585;

        System.out.println(String.format("%.1f", f));

        String c = ",已下单,平台已接单,已指派车队,已做单,";
//        System.out.println(c.contains(",已指派车队,"));


//        Calendar cal = Calendar.getInstance();
//        cal.setTime(DateUtil.parseDate("2021-06-17 13:11:12"));
//        cal.add(Calendar.MINUTE, 20);// 24小时制
//        Date date = cal.getTime();
//        System.out.println(DateUtil.formatDate(date));
        List<CarPosition> carPositionList = new ArrayList<>();
        CarPosition a = new CarPosition();
        a.setWarn(2);
        a.setBillId("a");
        carPositionList.add(a);
        a = new CarPosition();
        a.setWarn(3);
        a.setBillId("b");
        carPositionList.add(a);
        a = new CarPosition();
        a.setWarn(1);
        a.setBillId("c");
        carPositionList.add(a);

        carPositionList.sort((d, b) -> Integer.compare(d.getWarn(),b.getWarn()));
        System.out.println(1);
    }

//    @Scheduled(cron="0 30 07 * * ?")
    public void sendGzh() {
        JsonResult jr = syncListAndRemind(new CarPosition());
        List<CarPosition> carPositionList = (List<CarPosition>)jr.getData();
        String first = "";
        for (CarPosition cp: carPositionList) {
            if (cp.getWarn() != 0) {
                first += cp.getBillOfLading()+", "+cp.getDriver()+", "+cp.getDriverPhone()+" ";
            }
        }

        User u2 = new User();
        u2.setType("平台用户");
        u2.setOrganizationId(1);
        u2.setGzhId("not null");
        List<User> userList = userBiz.list(u2, new User(1));
        for (User u: userList) {
//            System.out.println(u.getGzhId()+"   "+ first+"   "+DateUtil.getCurrentDate());
            SettingGzh cm = new SettingGzh();
            TempSend tempSend2 = new TempSend();
            tempSend2.setTouser(u.getGzhId());
            tempSend2.setTemplateId("NmUIzARvtGDHaxf8PpXjMpU3H-Qy_5ZTj7St51Wd56s");
            tempSend2.setFirst(first);
            tempSend2.setKeyword1(DateUtil.getCurrentDate());
            tempSend2.setKeyword2("");
            tempSend2.setRemark("以上运单需要通知对应客服,销售和客户");
            tempSend2.setUrl("https://gzhsy.sszgjzx.com/trace");
            cm.setPrivateTemplate(tempSend2);
        }
    }

    @Override
    public JsonResult syncListAndRemind(CarPosition carPosition) {
        Bill bill3 = new Bill();
        if(carPosition!=null) {
            if(Utils.isNotEmpty(carPosition.getCustomer())){
                bill3.setCustomer(carPosition.getCustomer());
            }
            if(Utils.isNotEmpty(carPosition.getBillId())){
                bill3.setId(carPosition.getBillId());
            }
            if(Utils.isNotEmpty(carPosition.getVno())){
                bill3.setCarNo(carPosition.getVno());
            }
        }
        List<Bill> bills = billBiz.findCarName(bill3);
        String[] strs = {"",""};
        String vno = carPosition.getVno();
        if(bills != null && bills.size()>0) {
            for (Bill b: bills) {
                if(Utils.isNotEmpty(vno)){
                    vno = vno.replace(","+b.getCarNo(),"").replace(b.getCarNo(),"");
                }
                strs[0] += b.getCarNo()+"_2,";
                strs[1] += b.getId()+",";
            }
            strs[0] = strs[0].substring(0,strs[0].length()-1);
            strs[1] = strs[1].substring(0,strs[1].length()-1);
        }
        if(Utils.isNotEmpty(vno)){
            String[] vnos = vno.split(",");
            for (String s : vnos) {
                strs[0] += ","+s+"_2";
                strs[1] += ",无id";
            }
        }

        List<CarPosition> carPositions = ZjxlGps.vLastLocationV4(strs[0],strs[1]);
        List<CarPosition> carPositions2 = new ArrayList<>();
        if (carPositions != null && carPositions.size() > 0) {
            for (CarPosition c : carPositions) {
                for (Bill b: bills) {
                    if(c.getVno().equals(b.getCarNo())) {
                        AddressFactory addressFactory = new AddressFactory();
                        addressFactory.setBillId(b.getId());
                        List<AddressFactory> addressFactories = addressFactoryBiz.list(addressFactory, new User(1));
                        String add = "", addLL = "";

                        if (Utils.isNotEmpty(addressFactories)) {
                            AddressFactory af = addressFactories.get(0);
                            add = af.getFaddress();
                            addLL = af.getLongitude() + "," + af.getLatitude();
                            if (StringUtil.isBlank(af.getLongitude(), af.getLatitude()) || af.getLongitude().equals("null") ||af.getLatitude().equals("null")) {
                                break;
                            }
                        }
                        if (StringUtil.isBlank(b.getUpYardLongitude(), b.getUpYardLatitude()) || b.getUpYardLongitude().equals("null") ||b.getUpYardLatitude().equals("null")) {
                            break;
                        }
                        int red = 0,distance = 0,duration = 0;
                        String nine = DateUtil.getCurrentDate("yyyy-MM-dd")+" 09:30:00";
                        int ret = DateUtil.compareToDate(b.getPackDate(),nine,"yyyy-MM-dd hh:mm:ss");
                        if(ret <= 0) {
                            if (b.getState().equals("已提箱")) {
                                try {
//                                System.out.println("mapResult11:"+b.getUpYardLongitude()+"=" + b.getUpYardLatitude()+"=="+addLL);
                                    MapNavUtil mapResult=new MapNavUtil(b.getUpYardLongitude()+"," + b.getUpYardLatitude(), addLL, UserConstant.GAODE_MAP_KEY);
//                                System.out.println("mapResult22:"+mapResult.getResults().toString());
                                    distance = Integer.valueOf(mapResult.getResults().getDistance());
                                    duration = Integer.valueOf(mapResult.getResults().getDuration());
                                    Date arriver = DateUtil.addDatePlusMin(DateUtil.parseDate(DateUtil.getCurrentDate()), duration/60 + 60);
                                    if (DateUtil.compareToDate(arriver, DateUtil.parseDate(b.getPackDate())) > 0) {
                                        red = 1;
                                    }
                                    c.setDuration(DateUtil.formatDate(DateUtil.addDatePlusMin(DateUtil.parseDate(DateUtil.getCurrentDate()), duration/60)));
                                    c.setDistance(new BigDecimal(distance / 1000.0).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+"");
                                } catch (Exception e) {
                                    c.setDuration(DateUtil.formatDate(DateUtil.addDatePlusMin(DateUtil.parseDate(DateUtil.getCurrentDate()), 100000/60)));
                                    c.setDistance("10000");
                                }
                            } else if (b.getState().equals("已做单")){
                                red = 2;
                            }
                        }
                        c.setWarn(red);
                        c.setDriver(b.getDriver());
                        c.setDriverPhone(b.getDriverPhone());
                        c.setBillOfLading(b.getBillOfLading());
                        c.setCustomer(b.getCustomer());
                        c.setCarTeam(b.getCarTeam());
                        c.setFactoryAddress(add);
                        c.setAddressFactoryList(addressFactories);
                        c.setAddress(b.getAddress());
                        c.setUpyard(b.getUpYard());
                        c.setUpyardLongitude(b.getUpYardLongitude());
                        c.setUpyardLatitude(b.getUpYardLatitude());
                        c.setDock(b.getDock());
                        c.setDockLongitude(b.getDockLongitude());
                        c.setDockLatitude(b.getDockLatitude());
                        c.setState(b.getState());
                        c.setPackDate(b.getPackDate());
                        carPositions2.add(c);
                        try {
                            double[] gps = DistanceUtil.toTX(c.getLat() + "," + c.getLon());
                            c.setLat(gps[1]+"");
                            c.setLon(gps[0]+"");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                }

            }
        }
        carPositions2.sort((a, b) -> Integer.compare(b.getWarn(),a.getWarn()));
        return JsonResult.ok().setData(carPositions2);
    }

    @Override
    public JsonResult carPosition(CarPosition carPosition) {
        Bill bill3 = new Bill();
        if(carPosition!=null) {
            if(Utils.isNotEmpty(carPosition.getCustomer())){
                bill3.setCustomer(carPosition.getCustomer());
            }
            if(Utils.isNotEmpty(carPosition.getBillId())){
                bill3.setId(carPosition.getBillId());
            }
            if(Utils.isNotEmpty(carPosition.getVno())){
                bill3.setCarNo(carPosition.getVno());
            }
        }
        List<Bill> bills = billBiz.findCarName(bill3);
        String[] strs = {"",""};
        String vno = carPosition.getVno();
        if(bills != null && bills.size()>0) {
            for (Bill b: bills) {
                if(Utils.isNotEmpty(vno)){
                    vno = vno.replace(","+b.getCarNo(),"").replace(b.getCarNo(),"");
                }
                strs[0] += b.getCarNo()+"_2,";
                strs[1] += b.getId()+",";
            }
            strs[0] = strs[0].substring(0,strs[0].length()-1);
            strs[1] = strs[1].substring(0,strs[1].length()-1);
        }
        if(Utils.isNotEmpty(vno)){
            String[] vnos = vno.split(",");
            for (String s : vnos) {
                strs[0] += ","+s+"_2";
                strs[1] += ",无id";
            }
        }

        List<CarPosition> carPositions = ZjxlGps.vLastLocationV4(strs[0],strs[1]);
        if (carPositions != null && carPositions.size() > 0) {
            for (CarPosition c : carPositions) {
                for (Bill b: bills) {
                    if(c.getVno().equals(b.getCarNo())) {
                        c.setDriver(b.getDriver());
                        c.setDriverPhone(b.getDriverPhone());
                        c.setBillOfLading(b.getBillOfLading());
                        c.setCustomer(b.getCustomer());
                        c.setCarTeam(b.getCarTeam());
                        c.setFactoryAddress(b.getFactoryAddress());
                        c.setAddress(b.getAddress());
                        try {
                            double[] gps = DistanceUtil.toTX(c.getLat() + "," + c.getLon());
                            c.setLat(gps[1]+"");
                            c.setLon(gps[0]+"");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return JsonResult.ok().setData(carPositions);
    }

    @Override
    public JsonResult historyList(CarPosition carPosition) {
        List<CarPosition2> carPosition2s = carPositionDao.historyList(carPosition);
        return JsonResult.ok().setData(carPosition2s);
    }

    @Override
    public JsonResult historyListOriginal(CarPosition carPosition) {
        /*List<CarPosition2> carPosition2s = carPositionDao.historyList(carPosition);
        String[][] temp = null;
        if(carPosition2s != null && carPosition2s.size()>0){
            temp = new String[carPosition2s.size()][2];
            String[] temp2 = null;
            for(int i = 0; i < carPosition2s.size(); i ++){
                temp2 = new String[2];
                CarPosition2 c = carPosition2s.get(i);
                CarPosition c2 = GPSConverterUtils.transform(Double.parseDouble(c.getLon()),Double.parseDouble(c.getLat()));
                temp2[0] = c2.getLon();
                temp2[1] = c2.getLat();
                temp[i] = temp2;
            }
        }
        return JsonResult.ok().setData(temp);*/
        return null;
    }

    @Override
    public JsonResult checkTruckExist(CarPosition carPosition) {
        String s = ZjxlGps.checkTruckExist(carPosition.getVno());
        return JsonResult.ok().setData(s);
    }

    @Override
    public JsonResult checkVehicleExist(CarPosition carPosition) {
        String s = ZjxlGps.checkVehicleExist(carPosition.getVno());
        return JsonResult.ok().setData(s);
    }

    @Override
    public JsonResult findById(CarPosition carPosition) {
        return JsonResult.ok().setData(carPositionDao.findById(carPosition));
    }

    @Override
    public JsonResult suggestion(String keyword) {
        String sendGet = HttpsUtils.get2("https://apis.map.qq.com/ws/place/v1/suggestion?region=宁波市&region_fix=0&key="+ UserConstant.TX_MAP_KEY+"&keyword=" + keyword);
        JSONObject jsonObject=JSONObject.fromObject(sendGet);
        JsonResult jsonResult = new JsonResult();
        jsonResult.put("code", jsonObject.get("status"));
        jsonResult.put("data", jsonObject.get("data"));
        return jsonResult;
    }

    @Override
    public JsonResult save(CarPosition carPosition) {
        carPositionDao.save(carPosition);
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult saveBatch(List<CarPosition> carPositionList) {
        carPositionDao.saveBatch(carPositionList);
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult update(CarPosition carPosition) {
        carPositionDao.update(carPosition);
        return JsonResult.ok("修改成功");
    }

    @Override
    public JsonResult remove(CarPosition carPosition) {
        carPositionDao.remove(carPosition);
        return JsonResult.ok("删除成功");
    }

}
